package edu.stu.mall.activity.recommended

import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import edu.mall.base.BaseActivity
import edu.stu.mall.BR
import edu.stu.mall.MyApplication.Companion.context
import edu.stu.mall.R
import edu.stu.mall.adapter.ProductAttributeAdapter
import edu.stu.mall.databinding.ActivityProductDetailBinding
import edu.stu.mall.fragment.bottom.ProductBottomDialogFragment
import edu.stu.mall.service.loadImage

class ProductDetailActivity :
    BaseActivity<ActivityProductDetailBinding, ProductDetailViewHolder>() {
    private val productAttributeAdapter = ProductAttributeAdapter()

    override fun getLayoutId(): Int = R.layout.activity_product_detail

    override fun getViewModelId(): Int = BR.productDetailVm

    override fun initViewData() {
        intent.extras?.getString("id")?.let { productId ->
            Log.e("TAG", "initViewData: " + productId)
            viewModel?.getProductDetailData(productId)


            // 绑定productDetailData和productDetailData2的观察者
            bindProductDetailData()
        }
    }

    private fun bindProductDetailData() {
        viewModel?.productDetailData?.observe(this) {
            val brand = it.brand
            binding?.apply {
                tvBrandName.text = brand?.name
                tvFirstLetter.text = "品牌首字母：${brand?.name}"
                ivLogo?.let { logoView ->
                    loadImage(brand?.logo, logoView)
                }

                val bannerList = it.skuStockList
                    ?.mapNotNull { sku -> sku?.pic }
                    ?.distinct()
                    ?: mutableListOf()

                tvSpData.setOnClickListener {
//                    showSpDataBottomSheetDialog()
                    showSpDataBottomFrag()
                }

                tvAttribute.setOnClickListener {
                    showAttributeBottomSheetDialog(viewModel?.productAttributeValueMap?.value!!)
                }


                if (bannerList.isEmpty()) {

                    // 当 bannerList 为空时，使用品牌product.pic 作为背景图片
                    it.product?.pic?.let { logoUrl ->
                        Glide.with(context)
                            .asBitmap()
                            .load(logoUrl)
                            .into(object : CustomTarget<Bitmap>() {
                                override fun onResourceReady(
                                    resource: Bitmap,
                                    transition: Transition<in Bitmap>?
                                ) {
                                    // 将 logo 图片设置为 banner 背景
                                    val drawable = BitmapDrawable(resources, resource)
                                    binding?.banner?.background = drawable
                                }

                                override fun onLoadCleared(placeholder: Drawable?) {
                                    // 清理资源时的处理
                                }
                            })
                    } ?: run {
                        // 如果 logo 为空，设置背景颜色为红色
                        binding?.banner?.setBackgroundColor(Color.RED)
                    }
                } else {
                    binding?.banner?.apply {
                        setBackgroundColor(Color.TRANSPARENT)  // 有数据时去除背景
                        indicator = CircleIndicator(context)
                        setLoopTime(4000)
                        setIndicatorWidth(15, 15)
                        setAdapter(object : BannerImageAdapter<String>(bannerList) {
                            override fun onBindView(
                                holder: BannerImageHolder,
                                data: String,
                                position: Int,
                                size: Int
                            ) {
                                context?.let { ctx ->
                                    Glide.with(ctx).load(data).into(holder.imageView)
                                }
                            }
                        })
                    }
                }
            }

            it.product?.let {
                binding?.apply {
                    tvSale.text = "销量：${it.sale}"
                    tvStock.text = "库存：${it.stock}"
                    tvPrice.text = "￥：${it.price}"
                    tvName.text = it.name
                    tvSubName.text = it.subTitle
                    tvPrice.setTextColor(Color.RED)


                    binding?.wv?.apply {
                        settings.javaScriptEnabled = true
//                        settings.domStorageEnabled = true
                        settings.loadsImagesAutomatically = true

                        // 判断 detailHtml 是否为空或空字符串，若为空则使用 detailMobileHtml
                        val htmlContent = if (it.detailHtml?.length!! <= 0) {
                            Log.e(
                                "TAG",
                                "bindProductDetailData: if " + it.detailMobileHtml.toString()
                            )
                            it.detailMobileHtml.toString()
                        } else {
                            Log.e("TAG", "bindProductDetailData: else " + it.detailHtml.toString())
                            it.detailHtml.toString()
                        }

                        loadDataWithBaseURL(
                            null,
                            htmlContent,
                            "text/html",
                            "UTF-8",
                            null
                        )
                    }
                }
            }
        }
    }

    private fun showAttributeBottomSheetDialog(
        attributes: Map<String, String>,
    ) {
        // 使用 requireContext() 获取正确的 Context
        val bottomSheetDialog = BottomSheetDialog(this)

        // 为 BottomSheetDialog 设置布局
        val view: View = layoutInflater.inflate(R.layout.bottom_attribute, null)
        bottomSheetDialog.setContentView(view)


        // 显示 BottomSheetDialog
        bottomSheetDialog.show()


        productAttributeAdapter.setData(attributes!!)
        val rlv = view.findViewById<RecyclerView>(R.id.rlv)
        rlv.layoutManager = LinearLayoutManager(context)
        rlv.adapter = productAttributeAdapter
    }
    private fun showSpDataBottomFrag() {
        val productBottomDialogFragment=ProductBottomDialogFragment()
        productBottomDialogFragment.show(supportFragmentManager,"")

    }

    private fun showSpDataBottomSheetDialog() {
        // 使用 requireContext() 获取正确的 Context
        val bottomSheetDialog = BottomSheetDialog(this)

        // 为 BottomSheetDialog 设置布局
        val view: View = layoutInflater.inflate(R.layout.bottom_sp_data, null)
        bottomSheetDialog.setContentView(view)

        // 获取布局中的 Button，并设置点击事件
        val btnClose = view.findViewById<Button>(R.id.btnClose)
        btnClose.setOnClickListener {
            // 关闭 BottomSheetDialog
            bottomSheetDialog.dismiss()
        }

        // 显示 BottomSheetDialog
        bottomSheetDialog.show()
    }

}

